package com.LeeCode;

import java.util.*;

/**
 * 重排水果
 */

public class Code2561 {
    public static void main(String[] args) {
        int[] basket1 = {4, 4, 4, 4, 3}, basket2 = {5, 5, 5, 5, 3};
        System.out.println(new Code2561().minCost(basket1, basket2));
    }

    public long minCost(int[] basket1, int[] basket2) {
        int minCost = Integer.MAX_VALUE;
        Set<Integer> set = new HashSet<>();
        Map<Integer, Integer> cnt1 = new HashMap<>(), cnt2 = new HashMap<>();
        for (int num : basket1) {
            cnt1.merge(num, 1, Integer::sum);
            set.add(num);
            minCost = Math.min(minCost, num);
        }
        for (int num : basket2) {
            cnt2.merge(num, 1, Integer::sum);
            set.add(num);
            minCost = Math.min(minCost, num);
        }
        List<Integer> needMove = new ArrayList<>();
        for (int num : set) {
            int count1 = cnt1.getOrDefault(num, 0);
            int count2 = cnt2.getOrDefault(num, 0);
            if (((count1 + count2) & 1) == 1) return -1;
            int target = (count1 + count2) / 2;
            for (int i = 0; i < count1 - target; i++) needMove.add(num);
            for (int i = 0; i < count2 - target; i++) needMove.add(num);
        }

        long ans = 0;

        if (needMove.isEmpty()) return 0;
        Collections.sort(needMove);
        for (int i = 0; i < needMove.size() / 2; i++) {
            ans += Math.min(needMove.get(i), 2L * minCost);
        }
        return ans;
    }
}
